<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="./css/player.css" />
    <title>Document</title>
  </head>
  <body>
    <figure>
      <figcaption>视频播放器</figcaption>

      <div class="player">
        <video src="./xuanchuan.mp4"></video>

        <div class="controls">
          <!-- 播放/暂停 -->
          <a href="javascript:;" class="switch fa fa-play"></a>

          <!-- 全屏 -->
          <a href="javascript:;" class="expand fa fa-expand"></a>

          <!-- 进度条 -->
          <div class="progress">
            <div class="loaded"></div>
            <div class="line"></div>
            <div class="bar"></div>
          </div>

          <!-- 时间 -->
          <div class="timer">
            <span class="current">00:00:00</span> /
            <span class="total">00:00:00</span>
          </div>

          <!-- 声音 -->
        </div>
      </div>
    </figure>
    <script>
      let video = document.querySelector('video')
      let isPlay = document.querySelector('.switch')
      let expand = document.querySelector('.expand')
      let progress = document.querySelector('.progress')
      let loaded = document.querySelector('.progress > .loaded')
      let currPlayTime = document.querySelector('.timer > .current')
      let totalTime = document.querySelector('.timer > .total')

      // 当视频可播放时显示
      video.oncanplay = function() {
        // 显示视频
        this.style.display = 'block'
        // 显示视频总长度
        totalTime.innerHTML = getFormatTime(this.duration);
      }

      // 播放暂停
      isPlay.onclick = function() {
        if (video.paused) {
          video.play();
        } else {
          video.pause();
        }
        this.classList.toggle('fa-pause')
      }

      // 总时长和当前播放时长显示
      function getFormatTime( time = 0 ) {
        let h = parseInt(time/ 3600);
        let m = parseInt(time % 3600 / 60);
        let s = parseInt(time % 60);

        return h+":"+m+":"+s;
      }
      // 播放进度条
      video.ontimeupdate = function() {
        let currTime = this.currentTime; 
        let duration = this.duration;
        let per = currTime / duration * 100 + '%';
        // 显示进度条
        loaded.style.width = per;

        // 播放完成
        if (video.ended) {
          isPlay.classList.toggle('fa-pause')
        }

        // 显示当前播放进度时间
        currPlayTime.innerHTML = getFormatTime(currTime)
      }

      // 跳跃播放
      progress.onclick =  function(e) {
        let event = e || window.event;
        video.currentTime = (event.offsetX / this.offsetWidth) * video.duration;
      }

      //全屏
      expand.onclick = function(){
        video.webkitRequestFullScreen();
      };
    </script>
  </body>
</html>
